#include "task_manager.h"
#include <fstream>
#include <iostream>
#include <algorithm>
#include <ctime>
#include <iomanip>

using namespace std;


TaskManager::TaskManager(const string& dataFile) 
    : dataFile_(dataFile) {
    loadFromFile();
}

bool TaskManager::isUnique(const Task& task) const {
    for (const auto& t : tasks_) {
        // 检查名称和时间是否完全相同
        if (t.getName() == task.getName() && 
            t.getStartTime() == task.getStartTime()) {
            return false;
        }
        
        // 检查时间冲突（1小时内）
        if (abs(t.getStartTime() - task.getStartTime()) < 3600) {
            return false;
        }
    }
    return true;
}

bool TaskManager::addTask(const Task& task) {
    if (!isUnique(task)) {
        return false;
    }
    
    Task newTask = task;
    newTask.setId(nextId_++);
    tasks_.push_back(newTask);
    
    saveToFile();
    return true;
}

bool loadUserTasks(const string& username) {
// 清空当前任务列表
taskList.clear();

// 构建任务文件名
string filename = username + "_tasks.txt";

// 打开任务文件
ifstream taskFile(filename);
if (!taskFile.is_open()) {
cout << "no time txt" << endl;
return false;
}
string line;
int taskCount = 0;

cout << "Loading tasks from: " << filename << endl;

// 逐行读取任务
while (getline(taskFile, line)) {
// 跳过空行
if (line.empty()) continue;

try {
// 反序列化任务
Task task = Task::deserialize(line);
taskList.push_back(task);
taskCount++;
}
catch (const exception& e) {
cerr << "Error loading task: " << e.what() << endl;
cerr << "Invalid data: " << line << endl;
}
}

taskFile.close();
sortTasksByStartTimeAndSave(username);
cout << "Loaded " << taskCount << " tasks for user: " << username << endl;
return true;
}
 
bool TaskManager::deleteTask(int id) {
    auto it = remove_if(tasks_.begin(), tasks_.end(), 
        [id](const Task& t) { return t.getId() == id; });
    
    if (it != tasks_.end()) {
        tasks_.erase(it, tasks_.end());
        saveToFile();
        return true;
    }
    return false;
}

// 时间戳转换为可读字符串
string timeToString(time_t time) {
    if (time == 0) return "N/A";

    tm* timeinfo = localtime(&time);
    char buffer[80];
    strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", timeinfo);
    return string(buffer);
}
void xianshi(const vector<Task> taskList){
	cout << "ID    Name                Start Time            Priority  Category        needRemind\n";
        cout << "----------------------------------------------------------------------------------\n";

        for (const Task& task : taskList) {
            // 使用左对齐输出ID
            cout << left << setw(6) << task.getId()  // ID列宽度设为6，左对齐
                 << setw(20) << task.getName().substr(0, 19)
                 << setw(22) << timeToString(task.getStartTime());

            // 显示优先级 - 保持固定宽度
            switch (task.getPriority()) {
            case Task::LOW:
                cout << setw(10) << "Low";
                break;
            case Task::MEDIUM:
                cout << setw(10) << "Medium";
                break;
            case Task::HIGH:
                cout << setw(10) << "High";
                break;
            }

            // 显示类别 - 保持固定宽度
            switch (task.getCategory()) {
            case Task::STUDY:
                cout << setw(16) << "Study";
                break;
            case Task::ENTERTAINMENT:
                cout << setw(16) << "Entertainment";
                break;
            case Task::LIFE:
                cout << setw(16) << "Life";
                break;
            }
	switch(task.isReminded()){
		case true:
			cout<<setw(10)<<"Yes";
			break;
		case false:
			cout<<setw(10)<<"No";
			break;
	
	}
            cout << endl;
        }
    
}
// 查看特定日期、月份或年份的日程
void viewScheduleByDateRange() {
    	int choice;
   	cout << "Select time range to view:\n";
    	cout << "1. Specific day\n";
    	cout << "2. Entire month\n";
    	cout << "3. Entire year\n";
    	cout << "Enter your choice (1-3): ";
    	cin >> choice;

    	if (choice < 1 || choice > 3) {
        cerr << "Invalid choice. Please select 1, 2, or 3." << endl;
        return;
	}

    	string input;
    	tm timeInfo = {};
    	time_t startTime = 0;
    	time_t endTime = 0;

    	switch (choice) {
        case 1: // Specific day
            	cout << "Enter date (YYYY-MM-DD): ";
            	cin >> input;
            	if (strptime(input.c_str(), "%Y-%m-%d", &timeInfo) == nullptr) {
                	cerr << "Invalid date format. Please use YYYY-MM-DD." << endl;
                	return;
            	}
            	timeInfo.tm_isdst = -1;  // 自动处理夏令时
            	startTime = mktime(&timeInfo);
            	endTime = startTime + 24 * 3600 - 1;  // 当天23:59:59
            	break;

        case 2: // Entire month
            	cout << "Enter month (YYYY-MM): ";
            	cin >> input;
            	if (strptime(input.c_str(), "%Y-%m", &timeInfo) == nullptr) {
                	cerr << "Invalid month format. Please use YYYY-MM." << endl;
                	return;
            	}
            	timeInfo.tm_isdst = -1;
            	timeInfo.tm_mday = 1;  // 月份第一天
            	startTime = mktime(&timeInfo);
            
            	// 计算下个月的第一天
            	if (timeInfo.tm_mon == 11) {  // 12月
                	timeInfo.tm_year++;
                	timeInfo.tm_mon = 0;
            	} 
            	else {
                	timeInfo.tm_mon++;
            	}
            	endTime = mktime(&timeInfo) - 1;  // 下个月第一天的前一天23:59:59
            	break;

        case 3: // Entire year
            	cout << "Enter year (YYYY): ";
            	cin >> input;
            	if (strptime(input.c_str(), "%Y", &timeInfo) == nullptr) {
                	cerr << "Invalid year format. Please use YYYY." << endl;
                	return;
            	}
           	timeInfo.tm_isdst = -1;
            	timeInfo.tm_mon = 0;   // 一月
            	timeInfo.tm_mday = 1;  // 第一天
            	startTime = mktime(&timeInfo);
            
            	// 计算下一年的第一天
            	timeInfo.tm_year++;
            	endTime = mktime(&timeInfo) - 1;  // 下一年第一天的前一天23:59:59
            	break;
    	}

    	vector<Task> filteredTasks;
    
    	// 收集时间范围内的所有任务
    	for (const Task& task : taskList) {
        	time_t taskTime = task.getStartTime();
        	if (taskTime >= startTime && taskTime <= endTime) {
            		filteredTasks.push_back(task);
        	}
    	}

    // 如果没有任务，显示提示信息
    if (filteredTasks.empty()) {
        cout << "No tasks found for ";
        switch (choice) {
            case 1: cout << "day " << input; break;
            case 2: cout << "month " << input; break;
            case 3: cout << "year " << input; break;
        }
        cout << endl;
        return;
    }
    // 显示结果标题
    cout << "\nTasks for ";
    switch (choice) {
        case 1: cout << "day " << input; break;
        case 2: cout << "month " << input; break;
        case 3: cout << "year " << input; break;
    }
    cout << ":\n";
    xianshi(filteredTasks);
}



bool TaskManager::saveToFile() const {
    ofstream outFile(dataFile_);
    if (!outFile) {
        throw runtime_error("无法打开文件写入: " + dataFile_);
	return false;
    }
    
    for (const auto& task : tasks_) {
        outFile << task.serialize() << "\n";
    }
    outFile.close();
    return true;
}



const vector<Task>& TaskManager::getTasks() const {
    return tasks_;
}


bool saveTasksToFile(const string& username) {
    // 构建任务文件名
    string filename = username + "_tasks.txt";

    // 打开任务文件准备写入
    ofstream taskFile(filename);
    if (!taskFile.is_open()) {
        cerr << "Error: Unable to open file for writing: " << filename << endl;
        return false;
    }

    // 将每个任务序列化后写入文件
    for (const Task& task : taskList) {
        taskFile << task.serialize() << endl;
    }

    taskFile.close();
    return true;
}

// 按开始时间排序并保存
void sortTasksByStartTimeAndSave(const string& username) {
    // 使用lambda表达式作为比较函数，按开始时间升序排序
    sort(taskList.begin(), taskList.end(), 
        [](const Task& a, const Task& b) {
            return a.getStartTime() < b.getStartTime();
        });
    
    // 保存排序后的任务列表
    saveTasksToFile(username);
}
